package structures.sort;

import java.util.Arrays;

public class QuickSortDemo {

    private static final int LENGTH = 10;

    public static void main(String[] args) {
        // 生成数据
        int[] data = new int[LENGTH];
        for (int index = 0; index < data.length; index++) {
            data[index] = (int) (Math.random() * LENGTH);
        }

        // 打印数据
        System.out.println(Arrays.toString(data));

        long startTime = System.currentTimeMillis();
        quickSort(data, 0, data.length - 1);
        System.out.println("----------------消耗时间: " + (System.currentTimeMillis() - startTime) + " ms------------");

        // 打印数据
        System.out.println(Arrays.toString(data));
    }


    /**
     * 快排实现 选取参考点 迭代分左右 比较
     *
     * @param data  数据源
     * @param left  左边index
     * @param right 右边index
     */
    private static void quickSort(int[] data, int left, int right) {
        int i = left;
        int j = right;
        int temp;
        if (i < j) {
            temp = data[i];
            while (i < j) {
                while (j > i && data[j] >= temp) {
                    j--;
                }
                data[i] = data[j];

                while (i < j && data[i] <= temp) {
                    i++;
                }
                data[j] = data[i];
            }
//            System.out.println(Arrays.toString(data));
            data[i] = temp;
            quickSort(data, left, i - 1);
            quickSort(data, i + 1, right);
        }
    }
}
